// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //个人信息地址
    adress: {},
    //本地存储的已加入购物车的商品
    cart: [],
    // 全选框
    allChecked: false,
    // 总价格
    totalPrice: 0,
    //总数量
    totalNum: 0
  },

  //获取收获地址
  handleAdress() {
    wx.chooseAddress({
      success: (result) => {
        const adress = result;
        wx.setStorageSync('adress', adress)
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取地址
    const adress = wx.getStorageSync('adress');
    let cart = wx.getStorageSync('cart') || [];
    this.setCart(cart)
    this.setData({
      adress
    })
  },

  //商品的选中
  handeItemChange(e) {
    const goods_id = e.currentTarget.dataset.id;
    //获取购物车数组
    let { cart } = this.data;
    let index = cart.findIndex(v => v.goods_id === goods_id);
    cart[index].checked = !cart[index].checked

    this.setCart(cart)
  },

  //商品全选按钮
  handeItemAllChange() {
    let { cart, allChecked } = this.data;
    allChecked = !allChecked
    cart.forEach(item => item.checked = allChecked)
    this.setCart(cart)
  },

  //商品数目加减
  handeChaange(e) {
    const { id, addorcut } = e.currentTarget.dataset;
    // console.log(id,addorcut);
    let { cart } = this.data;
    const index = cart.findIndex(v => v.goods_id === id);
    if (cart[index].num === 1 && addorcut === -1) {
      wx.showModal({
        content: '是否从购物车移除此商品',
        title: '提示',
        success: (res) => {
          if (res.confirm) {
            cart.splice(index, 1);
            this.setCart(cart)
          }
        }
      })
    } else {
      cart[index].num += addorcut;
    }
    this.setCart(cart)
  },

  //提交订单
  onClickButton() {
    // console.log(123);
    const { adress, totalNum } = this.data;
    if (!adress.userName) {
      wx.showToast({
        title: '请添加收货地址',
        icon: 'error'
      })
    }
    if (totalNum === 0) {
      wx.showToast({
        title: '请添加商品',
        icon: 'error'
      })
    }
    wx.navigateTo({
      url: '/pages/pay/index',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  setCart(cart) {
    wx.setStorageSync('cart', cart);
    //计算全选
    const allChecked = cart.length ? cart.every(item => item.checked) : false;
    //计算总价格总数
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(item => {
      if (item.checked) {
        totalPrice += item.num * item.goods_price;
        totalNum += item.num;
      }
    })
    this.setData({
      cart,
      totalNum,
      totalPrice,
      allChecked
    });
  }
})